﻿using admin.cyt369.com.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace admin.cyt369.com.Controllers
{
    public partial class AdminController : Admin.CYT369.Com.WebBase.AllowAnonymousController
    {
        private static System.Text.StringBuilder m_Resp = new System.Text.StringBuilder();
        private Microsoft.AspNetCore.Identity.UserManager<Admin.CYT369.Com.DAL.Domains.SysUser> m_UserManager;

        public AdminController(Microsoft.AspNetCore.Identity.UserManager<Admin.CYT369.Com.DAL.Domains.SysUser> userManager)
        {
            m_UserManager = userManager;
        }

        public async Task<IActionResult> CreateDB()
        {
            var ctx = new Admin.CYT369.Com.DAL.DbContexts.AdminContext();

            m_Resp.AppendLine("开始创建数据库......");

            ctx.Database.EnsureCreated();
            m_Resp.AppendLine("................................数据库创建成功.");

            await InitData(ctx);


            return Content(m_Resp.ToString());
        }



        private async Task InitData(Admin.CYT369.Com.DAL.DbContexts.AdminContext context)
        {
            #region 初始化系统账户
            m_Resp.AppendLine("开始初始化系统账户.......");
            var administrator = new Admin.CYT369.Com.DAL.Domains.SysUser()
            {
                UserName = "Administrator",
                Email = "admin@qq.com",
                PhoneNumber = "13800138000",
            };
            var result = await m_UserManager.CreateAsync(administrator, "123456");

            if (result.Succeeded)
            {
                m_Resp.AppendLine("................................初始化系统账户完成.");
            }
            else
            {
                m_Resp.AppendLine("................................初始化系统账户失败");
                foreach (var e in result.Errors)
                {
                    m_Resp.AppendLine(e.Description);
                }
            }
            #endregion

        }



    }
}
